import jwt from 'jsonwebtoken';
import { User } from '@/entities/system/user.entity';
import { ErrorHandler } from '@/middlewares/error.middleware';
import { TokenManager } from '@/config/redis';

// JWT 密钥，实际项目应存储在环境变量中
const JWT_SECRET = 'dashengfufa-jwt-secret-key';
const TOKEN_EXPIRE = '24h'; // Token 有效期为24小时

export interface TokenPayload {
  id: string;
  username: string;
  email:string;
}

/**
 * 生成 JWT Token
 * @param user 用户信息
 * @returns JWT Token
 */
export const generateToken = (user: User): string => {
  const payload: TokenPayload = {
    id: user.id,
    username: user.username,
    email:user.email,
  };

  return jwt.sign(payload, JWT_SECRET, { expiresIn: TOKEN_EXPIRE });
};

/**
 * 验证 JWT Token
 * @param token JWT Token
 * @returns 解析后的用户信息
 */
export const verifyToken = async (token: string): Promise<TokenPayload> => {
  try {
    const payload = jwt.verify(token, JWT_SECRET) as TokenPayload;
    
    // 检查token是否为用户当前有效的token（使用Redis）
    const isValid = await TokenManager.validateUserToken(payload.id, token);
    if (!isValid) {
      throw new ErrorHandler('Token已失效，请重新登录', 401);
    }
    
    return payload;
  } catch (error) {
    if (error instanceof ErrorHandler) {
      throw error;
    }
    throw new ErrorHandler('无效的 Token', 401);
  }
};
